package com.guagua.blog.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.guagua.blog.dto.ArticleDTO;
import com.guagua.blog.entity.Article;
import com.guagua.blog.service.ArticleService;
import com.guagua.blog.service.ViewLogService;
import com.guagua.common.response.Result;
import com.guagua.system.security.SecurityUtils;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.security.SecurityRequirement;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.List;

@Tag(name = "文章管理", description = "文章相关接口")
@RestController
@RequestMapping("/api/articles")
@RequiredArgsConstructor
public class ArticleController {
    
    private final ArticleService articleService;
    private final ViewLogService viewLogService;
    
    @Operation(summary = "分页获取文章列表")
    @GetMapping
    public Result<IPage<Article>> getArticleList(
            @RequestParam(defaultValue = "1") int page,
            @RequestParam(defaultValue = "10") int size,
            @RequestParam(required = false) Long tagId) {
		IPage<Article> pageResult = articleService.getArticlesByTag(tagId, page, size);
        return Result.success(pageResult);
    }
    
    @Operation(summary = "获取文章详情")
    @GetMapping("/{id}")
    public Result<Article> getArticleDetail(@PathVariable Long id) {
        Article article = articleService.getArticleDetail(id);
        return Result.success(article);
    }
    
    @PostMapping
    @Operation(summary = "发布文章")
    @SecurityRequirement(name = "Authorization")
    public Result<Long> createArticle(@RequestBody @Valid ArticleDTO articleDTO) {
        Long userId = SecurityUtils.getCurrentUserId();
        Article article = new Article();
        article.setTitle(articleDTO.getTitle());
        article.setContent(articleDTO.getContent());
        article.setDescription(articleDTO.getDescription());
        article.setCoverImage(articleDTO.getCoverImage());
        article.setAuthorId(userId);
        article.setCreateTime(LocalDateTime.now());
        article.setUpdateTime(LocalDateTime.now());
        
        // 保存文章并获取文章ID
        articleService.save(article);
        
        // 保存文章标签关联
        if (articleDTO.getTags() != null && !articleDTO.getTags().isEmpty()) {
            articleService.saveArticleTags(article.getId(), articleDTO.getTags());
        }
        
        return Result.success(article.getId());
    }
    
    @Operation(summary = "更新文章")
    @PutMapping("/{id}")
    @SecurityRequirement(name = "Authorization")
    public Result<Boolean> update(@Parameter(description = "文章ID") @PathVariable Long id, 
                                @RequestBody Article article) {
        article.setId(id);
        return Result.success(articleService.updateById(article));
    }
    
    @Operation(summary = "删除文章")
    @DeleteMapping("/{id}")
    @SecurityRequirement(name = "Authorization")
    public Result<Boolean> delete(@Parameter(description = "文章ID") @PathVariable Long id) {
        return Result.success(articleService.removeById(id));
    }

    @GetMapping("/hot")
    @Operation(summary = "获取热门文章")
    public Result<List<Article>> getHotArticles() {
        List<Article> articles = articleService.getHotArticles();
        return Result.success(articles);
    }

    @PostMapping("/{id}/view")
    @Operation(summary = "记录文章浏览")
    public Result<Void> recordView(@PathVariable Long id, HttpServletRequest request) {
        String ip = request.getRemoteAddr();
        viewLogService.recordView(id, ip);
        return Result.success();
    }

    @GetMapping("/favorites")
    @Operation(summary = "获取用户收藏的文章列表")
    @SecurityRequirement(name = "Authorization")
    public Result<IPage<Article>> getFavoriteArticles(
            @RequestParam(defaultValue = "1") int page,
            @RequestParam(defaultValue = "10") int size) {
        Long userId = SecurityUtils.getCurrentUserId();
        IPage<Article> articles = articleService.getFavoriteArticles(userId, page, size);
        return Result.success(articles);
    }

    @GetMapping("/read")
    @Operation(summary = "获取用户已读的文章列表")
    @SecurityRequirement(name = "Authorization")
    public Result<IPage<Article>> getReadArticles(
            @RequestParam(defaultValue = "1") int page,
            @RequestParam(defaultValue = "10") int size) {
        Long userId = SecurityUtils.getCurrentUserId();
        IPage<Article> articles = articleService.getReadArticles(userId, page, size);
        return Result.success(articles);
    }

    @GetMapping("/liked")
    @Operation(summary = "获取用户点赞的文章列表")
    @SecurityRequirement(name = "Authorization")
    public Result<IPage<Article>> getLikedArticles(
            @RequestParam(defaultValue = "1") int page,
            @RequestParam(defaultValue = "10") int size) {
        Long userId = SecurityUtils.getCurrentUserId();
        IPage<Article> articles = articleService.getLikedArticles(userId, page, size);
        return Result.success(articles);
    }

    @GetMapping("/user")
    @Operation(summary = "获取当前用户的文章列表")
    @SecurityRequirement(name = "Authorization")
    public Result<IPage<Article>> getUserArticles(
            @RequestParam(defaultValue = "1") int page,
            @RequestParam(defaultValue = "10") int size) {
        Long userId = SecurityUtils.getCurrentUserId();
        IPage<Article> articles = articleService.getUserArticles(userId, page, size);
        return Result.success(articles);
    }
} 